package com.example.gobang2.controller;

import com.example.gobang2.game.Match;
import com.example.gobang2.game.MatchRequest;
import com.example.gobang2.game.MatchResponse;
import com.example.gobang2.game.OnlineUserManager;
import com.example.gobang2.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class MatchController extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    OnlineUserManager onlineUserManager;
    @Autowired
    Match match;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get("user");
        if(user == null){
            System.out.println("[MatchController] 用户未登录！userId="+user.getUserId());
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("玩家未登录！");
            response.setMessage("");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsBytes(response)));
            return;
        }
        if(onlineUserManager.getSessionFromGameHall(user.getUserId())!=null||onlineUserManager.getSessionFromGameRoom(user.getUserId())!=null){
            MatchResponse response = new MatchResponse();
            response.setMessage("");
            response.setOk(false);
            response.setReason("玩家重复登录！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
            return;
        }
        onlineUserManager.enterGameHall(user.getUserId(),session);
        System.out.println("[MatchController] 玩家："+user.getUsername()+"进入游戏大厅！");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User user = (User) session.getAttributes().get("user");
        if(user==null){
            System.out.println("[MatchController] 玩家尚未登录！");
            return;
        }
        WebSocketSession exitSession = onlineUserManager.getSessionFromGameHall(user.getUserId());
        if(session!=exitSession){
            System.out.println("[MatchController] Error当前会话不是玩家的会话！");
            return;
        }
        onlineUserManager.removeGameHall(user.getUserId());
        match.remove(user);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)  {
        User user = (User) session.getAttributes().get("user");
        if(user==null){
            System.out.println("[MatchController] 玩家尚未登录！");
            return;
        }
        WebSocketSession exitSession = onlineUserManager.getSessionFromGameHall(user.getUserId());
        if(session!=exitSession){
            System.out.println("[MatchController] ConnectionEstablished当前会话不是玩家的会话！");
            System.out.println("session="+session.getAttributes().get("user"));
            return;
        }
        onlineUserManager.removeGameHall(user.getUserId());
        match.remove(user);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        if(user == null){
            System.out.println("[MatchController] 用户未登录！userId="+user.getUserId());
            return;
        }
        System.out.println("[MatchController] 玩家:"+user.getUsername()+"开始匹配！");
        MatchRequest request = objectMapper.readValue(message.getPayload(),MatchRequest.class);
        String payload = request.getMessage();
        MatchResponse response = new MatchResponse();
        if("StartMatch".equals(payload)){
            response.setOk(true);
            response.setMessage("StartMatch");
            match.add(user);
        }else if("StopMatch".equals(payload)){
            response.setOk(true);
            response.setMessage("StopMatch");
            match.remove(user);
        }else{
            response.setOk(false);
            response.setReason("非法的请求！");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

}
